package cn.app.android.sichuanxiaoke.com.xiaokeapp.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import cn.app.android.sichuanxiaoke.com.xiaokeapp.R;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.ConstantUtils;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.PayListener;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.PaySDK;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.PaySDKFactory;
import okhttp3.OkHttpClient;

public class GoPayAppActivity extends AppCompatActivity {

    private Map<String, Object> message = null;
    private long startTime, endTime;
    private PaySDK paySDK = null;
    private static boolean isFirst = true;

    //public static String PATH = "https://omnipay.cib.cibfintech.com/appserver/service/GenOrderService.r";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_go_pay_app);
        paySDK = PaySDKFactory.getInstance(this);
        startTime = System.currentTimeMillis();
        Intent intent = getIntent();
        String packageName = intent.getStringExtra("packageName");
        Log.i("packageName","-----"+packageName);
        intent.setComponent(new ComponentName("cc.rengu.android.pay.ipps", "cc.rengu.android.ui.activity.CollectionMoney"));
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", (Serializable) intent.getExtras().get("data"));
        intent.putExtras(bundle);
        try {
            startActivityForResult(intent, PaySDK.REQ_PAY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "没有支付APP，请下载安装", Toast.LENGTH_SHORT).show();
            this.finish();
        }
        //BandEvent();
        //initView();
    }

    private void BandEvent() {

    }

    private void initView() {
        Intent intent = getIntent();
        String moneyNumber = intent.getStringExtra("moneyNumber");
        /**
         *因为兴业银行的交易是以“分” 为单位，我们输入的是以“元为单位” 所以将元转换成分
         */
        float i = Float.valueOf(moneyNumber);
        final int newmoneyNumber= (int) (i*100);
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void run() {
                JSONObject data = new JSONObject();
                try {
                    data.put("appid", "1100011000");
                    data.put("phone", "40WX4I0M01");
                    data.put("amount", String.valueOf(newmoneyNumber));
                    data.put("mchnt_no", "309044353310001");
                    data.put("trans_type", "01");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                OkGo.<String>post(ConstantUtils.CREATE_ORDER_URL)
                        .upJson(data.toString())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String s = response.toString();
                                String body = response.body();
                                try {
                                    JSONObject object = new JSONObject(body);
                                    String orderId = object.optString("order_id");
                                    GoPay(orderId);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Log.i("TAG", "Success---" + body);
                            }

                            @Override
                            public void onError(Response<String> response) {

                                Log.e("TAG", response.toString());

                                response.getException().printStackTrace();
                            }
                        });

            }
        }).start();
    }

    private void GoPay(String mchntNo) {
        String contextString = this.toString();
        String clsName = contextString.substring(0, contextString.indexOf("@"));

        Map<String, Object> map = new HashMap();
        map.put("mchntNo", "309044353310001");
        map.put("phone", "40WX4I0M01");
        map.put("opeNum", "01");
        map.put("terminalNo", "43003726");
        map.put("mchntName", "hahah");
        map.put("transType", "cardPay");
        map.put("transactionId", mchntNo);

        Intent intent = new Intent();
        ComponentName name = new ComponentName("cc.rengu.android.pay.ipps"
                , "cc.rengu.android.ui.activity.CollectionMoney");
        intent.setComponent(name);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", (Serializable) map);
        bundle.putString("clsName", clsName);
        intent.putExtras(bundle);
        Log.i("return_msg", "往支付app发送的数据为=" + map);
        try {
            startActivityForResult(intent, PaySDK.REQ_PAY);
        }catch (Exception e){
            Toast.makeText(this,"请先安装支付插件",Toast.LENGTH_SHORT).show();
        }
        finish();

    }
    @Override
    protected void onResume() {
        super.onResume();
        isFirst = isFirst == true ? false : true;
        if (isFirst) {
            Log.e("PaySdkActivity", "onResume()方法 ");
            endTime = System.currentTimeMillis();
            if ((endTime - startTime) <= 600 * 1000 && message != null) {
                paySDK.sendSuccess(message);
                this.finish();
            } else {
                if ((endTime - startTime) > 600 * 1000) {
                    //paySDK.sendFail("交易超时,请重新支付");
                } else {
                    //paySDK.sendFail("交易失败");
                }
                this.finish();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("cellback","--------Huidao --");

        if (requestCode == PaySDK.REQ_PAY && resultCode == RESULT_OK) {
            HashMap<String, Object> info = null;
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    info= (HashMap<String, Object>) bundle.get("result");
                    String resCode = (String) info.get("resCode");
                    Intent intent=new Intent(GoPayAppActivity.this,PaySuccessWebviewActivity.class);
                    if(resCode.equals("OK")){
                        intent.putExtra("status",1);
                    }else {
                        intent.putExtra("status",0);
                    }
                    startActivity(intent);
                    finish();
                }
            }

        }

    }

    //返回键不可用
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        } else {
            return false;
        }
    }
}
